import {useState} from "react";

interface UseUploadPhoto {
    selectedFile: File | null;
    setSelectedFile: (file: File | null) => void;
    handleFileChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
    handleUploadPhoto: () => Promise<void>;
    uploadStatus: string | null;
}

export function useUploadPhoto(): UseUploadPhoto {
    const [selectedFile, setSelectedFile] = useState<File | null>(null);
    const [uploadStatus, setUploadStatus] = useState<string | null>(null);

    const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        const files = event.target.files;
        if (files && files.length > 0) {
            setSelectedFile(files[0]);
        }
    };

    const handleUploadPhoto = async () => {
        if (!selectedFile) {
            return;
        }

        const formData = new FormData();
        formData.append('image', selectedFile);

        const token = localStorage.getItem('token');

        try {
            if (!token) {
                return;
            }
            const response = await fetch('http://localhost:6868/employee/uploadAttendancePhoto', {
                method: 'POST',
                headers: {
                    'Authorization': token!
                },
                body: formData,
            });

            if (!response.ok) {
                throw new Error('上传失败');
            }

            setUploadStatus('上传成功');
        } catch (error) {
            console.error('上传失败', error);
            setUploadStatus('上传失败');
        }
    };

    return {
        selectedFile,
        setSelectedFile,
        handleFileChange,
        handleUploadPhoto,
        uploadStatus,
    };
}
